﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using LevenBlog.Core.Utils;

namespace LevenBlog.Core.Install {
    public static class InstallConfigService {
        private static readonly string _path = "~/install/install.config";

        private static string getRealPath() {
            return Fetch.MapPath(_path);
        }

        public static InstallConfig Read() {
            string path = getRealPath();
            if (!File.Exists(path)) {
                throw new FileNotFoundException(_path);
            }
            InstallConfig result = null;
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                XmlSerializer xs = new XmlSerializer(typeof(InstallConfig));
                try {
                    result = xs.Deserialize(fs) as InstallConfig;
                } catch { }
            }
            return result;
        }

        public static void Write(InstallConfig config) {
            if (config == null)
                throw new ArgumentNullException("config");
            string path = getRealPath();
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) {
                XmlSerializer xs = new XmlSerializer(typeof(InstallConfig));
                xs.Serialize(fs, config);
            }
        }
    }
}
